<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        width: 200px;
        height: 200px;
        font: 45px/55px "";
        color: white;
        text-align: center;
        background-color: hotpink;
        cursor: move;
        position: absolute;
    }
</style>

<body>
    <div class="box"></div>
</body>
<script>
    //1.获取元素
    let box = document.querySelector(".box")
    // console.log(box)
    //2.给获取到的元素添加事件
    box.onmousedown = function (e) {
        let clientWidth = document.documentElement.clientWidth
        let clientHeight = document.documentElement.clientHeight
        //获取鼠标在盒子中的位置
        let ofX = e.offsetX
        let ofY = e.offsetY
        // 注册一个鼠标移动事件
        document.onmousemove = function (e) {
            let x = e.pageX - ofX
            let y = e.pageY - ofY

            if (x <= 100) {
                x = 0
            }
            if (y <= 100) {
                y = 0
            }
            if (clientWidth - (x + box.offsetWidth) <= 100) {
                x = clientWidth - box.offsetWidth
            }
            if (clientHeight - (y + box.offsetHeight) <= 100) {
                y = clientHeight - box.offsetHeight
            }
            console.log(x)
            console.log(y)
            box.style.left = x + "px"
            box.style.top = y + "px"
        }
    }
    box.onmouseup = function () {
        document.onmousemove = null
    }
</script>

</html>

<!-- 
//获取客户端的长宽
let clientWidth = document.documentElement.clientWidth
let clientHeight = document.documentElement.clientHeight
// console.log(clientWidth)
// console.log(clientHeight) -->